import markdownIt from "./npm/markdown-it@14.1.0/%2Besm"
import markdownIt_footnote from "./npm/markdown-it-footnote@4.0.0/%2Besm"
import markdownIt_mark from "./npm/markdown-it-mark@4.0.0/%2Besm"
import markdownIt_sub from "./npm/markdown-it-sub@2.0.0/%2Besm"
import markdownIt_sup from "./npm/markdown-it-sup@2.0.0/%2Besm"
//import MarkdownItMathJaX3PRO from '/npm/markdown-it-mathjax3-pro@1.0.0/%2Besm';
//import markdownItTexmath from './npm/markdown-it-texmath@1.0.0/%2Besm';
import { full as markdownIt_emoji } from "./npm/markdown-it-emoji@3.0.0/%2Besm"
import markdownIt_InlineMathBypasser from './markdown-it-InlineMathBypasser.js'
import markdownIt_BlockMathBypasser from './markdown-it-BlockMathBypasser.js'
//import markdownItMathjax3 from './npm/markdown-it-mathjax3@5.2.0/%2Besm'
import hljs from './npm/highlight.js@11.11.1/%2Besm'

const md = new markdownIt({
    html: true,
    linkify: true,  // 自动识别文本中的 URL
    highlight: function (str, lang) {
        if (lang && hljs.getLanguage(lang)) {
            try {
                return hljs.highlight(str, { language: lang }).value;
            } catch (__) { }
        }
        return ''; // use external default escaping
    }
}).use(markdownIt_footnote).use(markdownIt_mark).use(markdownIt_sub).use(markdownIt_sup).use(markdownIt_emoji).use(markdownIt_InlineMathBypasser).use(markdownIt_BlockMathBypasser);

window.addEventListener("load", () => {
    const CurrentFilenameDisplay = document.getElementById("CurrentFilenameDisplay");
    LoadLastOpenedFile();
});

function replacePlusInSrc(htmlString) {  // 将所有src="..."中的加号修正为%2B，因为nanohttpd有天生残疾，加号会被一律转换为空格
    // 使用正则表达式匹配src属性及其值
    // 正则表达式解释:
    // src\s*=\s*["'] 匹配src=及其前后可能的空格和引号
    // ([^"']*) 捕获引号内的内容(不包含引号)
    // ["'] 匹配结束引号
    return htmlString.replace(/src\s*=\s*["']([^"']*)["']/gi, function(match, srcValue) {
        // 将src值中的所有加号替换为%2B
        const modifiedSrc = srcValue.replace(/\+/g, '%2B').replace(/ /g, '%20');
        // 返回修改后的整个src属性
        return `src="${modifiedSrc}"`;
    });
}

async function LoadLastOpenedFile() {
    const response = await fetch("/POST_GetMarkdownSource", {
        method: 'POST',
    })
    if (response.ok) {
        const MDSource = await response.text();
        const ast = md.parse(MDSource, {});
        const HTMLSource = md.renderer.render(ast, md.options, {});
        const NoteRenderDisplayer = document.getElementById("NoteRenderDisplayer");
        NoteRenderDisplayer.innerHTML = replacePlusInSrc(HTMLSource);
//        const elements = document.getElementsByTagName('eqn');
//        console.log(elements);
        // 处理每个 eqn 标签
//        MathJax.typeset(Array.from(elements)).then(() => {
//            console.log('eqn 标签内的公式已渲染完成');
//        });
//        alert(HTMLSource);
        MathJax.typeset();
    }
}